<template>
  <view class="publish-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left" @tap="cancelPublish">
        <text class="cancel-text">取消</text>
      </view>
      <text class="nav-title">发布动态</text>
      <view class="nav-right" @tap="publish" :class="{ disabled: !canPublish }">
        <text class="publish-text">发布</text>
      </view>
    </view>

    <!-- 内容输入区域 -->
    <view class="content-input-section">
      <view class="user-info">
        <image :src="userInfo.avatar" class="user-avatar" mode="aspectFill"></image>
        <text class="user-name">{{ userInfo.name }}</text>
      </view>
      <textarea class="content-textarea" placeholder="分享你的想法..." v-model="content" @input="onContentInput"
        :maxlength="200" auto-height></textarea>
      <text class="word-count">{{ content.length }}/200</text>
    </view>

    <!-- 图片选择区域 -->
    <view class="image-select-section">
      <view class="image-list">
        <view class="image-item upload-btn" @tap="chooseImage" v-if="images.length < maxImages">
          <text class="upload-icon">+</text>
        </view>
        <view class="image-item" v-for="(img, index) in images" :key="index">
          <image :src="img" class="selected-image" mode="aspectFill"></image>
          <view class="delete-icon" @tap.stop="deleteImage(index)">✕</view>
        </view>
      </view>
      <text class="image-tip">最多上传9张图片</text>
    </view>

    <!-- 添加话题区域 -->
    <view class="topic-section">
      <view class="topic-label">添加话题</view>
      <view class="topic-list">
        <view class="topic-item" v-for="(topic, index) in selectedTopics" :key="index">
          <text class="topic-text">#{{ topic }}#</text>
          <view class="topic-delete" @tap.stop="deleteTopic(index)">✕</view>
        </view>
        <view class="topic-item add-topic" @tap="showTopicPanel">
          <text class="add-topic-text">添加话题</text>
        </view>
      </view>
    </view>

    <!-- 隐私设置 -->
    <view class="privacy-section">
      <text class="privacy-label">谁可以看</text>
      <view class="privacy-options">
        <view class="privacy-option" :class="{ active: privacy === 'public' }" @tap="setPrivacy('public')">
          <text>公开</text>
          <image v-if="privacy === 'public'" src="/static/logo.png" class="selected-icon" mode="aspectFill"></image>
        </view>
        <view class="privacy-option" :class="{ active: privacy === 'followers' }" @tap="setPrivacy('followers')">
          <text>关注的人可见</text>
          <image v-if="privacy === 'followers'" src="/static/logo.png" class="selected-icon" mode="aspectFill"></image>
        </view>
        <view class="privacy-option" :class="{ active: privacy === 'private' }" @tap="setPrivacy('private')">
          <text>私密</text>
          <image v-if="privacy === 'private'" src="/static/logo.png" class="selected-icon" mode="aspectFill"></image>
        </view>
      </view>
    </view>

    <!-- 话题选择面板 -->
    <view class="topic-panel" v-if="showTopicPanel">
      <view class="panel-header">
        <text class="panel-title">选择话题</text>
        <view class="panel-close" @tap="closeTopicPanel">✕</view>
      </view>
      <view class="hot-topics">
        <text class="hot-topics-title">热门话题</text>
        <view class="hot-topics-list">
          <view class="hot-topic-item" v-for="(topic, index) in hotTopics" :key="index" @tap="selectTopic(topic.name)">
            <text class="hot-topic-name">#{{ topic.name }}#</text>
            <text class="hot-topic-count">{{ topic.count }}人参与</text>
          </view>
        </view>
      </view>
      <view class="recent-topics" v-if="recentTopics.length > 0">
        <text class="recent-topics-title">最近使用</text>
        <view class="recent-topics-list">
          <view class="recent-topic-item" v-for="(topic, index) in recentTopics" :key="index" @tap="selectTopic(topic)">
            <text class="recent-topic-name">#{{ topic }}#</text>
          </view>
        </view>
      </view>
      <view class="custom-topic">
        <input type="text" class="custom-topic-input" placeholder="输入自定义话题名称" v-model="customTopic"
          @confirm="addCustomTopic" />
        <view class="custom-topic-btn" @tap="addCustomTopic" :class="{ disabled: !customTopic.trim() }"><text>添加</text>
        </view>
      </view>
    </view>

    <!-- 发布中遮罩 -->
    <view class="loading-mask" v-if="publishing">
      <view class="loading-content">
        <text class="loading-text">发布中...</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { ref, computed } from 'vue';

// 用户信息
const userInfo = ref({
  name: '我',
  avatar: '/static/logo.png'
});

// 内容
const content = ref('');
// 图片列表
const images = ref([]);
const maxImages = 9;
// 选中的话题
const selectedTopics = ref([]);
// 隐私设置
const privacy = ref('public'); // public, followers, private
// 发布状态
const publishing = ref(false);
// 话题面板
const showTopicPanel = ref(false);
const hotTopics = ref([
  { name: '恋爱日常', count: 2568 },
  { name: '城市生活', count: 1892 },
  { name: '美食分享', count: 3256 },
  { name: '旅行日记', count: 1567 },
  { name: '摄影技巧', count: 987 },
  { name: '读书分享', count: 876 },
  { name: '职场经验', count: 1234 },
  { name: '健身打卡', count: 2109 }
]);
const recentTopics = ref(['恋爱日常', '城市生活']);
const customTopic = ref('');

// 计算是否可以发布
const canPublish = computed(() => {
  return content.value.trim().length > 0 || images.length > 0;
});

// 页面加载时
onLoad(() => {
  console.log('发布页面加载');
  // 获取用户信息
  const userInfoStorage = uni.getStorageSync('userInfo');
  if (userInfoStorage) {
    try {
      const parsedUserInfo = JSON.parse(userInfoStorage);
      userInfo.value = parsedUserInfo;
    } catch (error) {
      console.error('解析用户信息失败:', error);
    }
  }
});

// 取消发布
const cancelPublish = () => {
  if (content.value.trim() || images.length > 0) {
    uni.showModal({
      title: '提示',
      content: '确定要放弃编辑吗？',
      success: (res) => {
        if (res.confirm) {
          uni.navigateBack();
        }
      }
    });
  } else {
    uni.navigateBack();
  }
};

// 内容输入事件
const onContentInput = (e) => {
  content.value = e.detail.value;
};

// 选择图片
const chooseImage = () => {
  const count = maxImages - images.length;

  uni.chooseMedia({
    count: count,
    mediaType: ['image'],
    sourceType: ['album', 'camera'],
    sizeType: ['compressed'],
    success: (res) => {
      const tempFilePaths = res.tempFiles.map(file => file.tempFilePath);
      images.value = [...images.value, ...tempFilePaths];
    },
    fail: (err) => {
      console.error('选择图片失败:', err);
    }
  });
};

// 删除图片
const deleteImage = (index) => {
  images.value.splice(index, 1);
};

// 设置隐私
const setPrivacy = (type) => {
  privacy.value = type;
};

// 显示话题面板
const showTopicPanel = () => {
  showTopicPanel.value = true;
};

// 关闭话题面板
const closeTopicPanel = () => {
  showTopicPanel.value = false;
  customTopic.value = '';
};

// 选择话题
const selectTopic = (topicName) => {
  // 检查是否已添加该话题
  if (!selectedTopics.value.includes(topicName)) {
    selectedTopics.value.push(topicName);

    // 更新最近使用的话题
    if (!recentTopics.value.includes(topicName)) {
      recentTopics.value.unshift(topicName);
      if (recentTopics.value.length > 10) {
        recentTopics.value.pop();
      }
    }
  }
  closeTopicPanel();
};

// 删除话题
const deleteTopic = (index) => {
  selectedTopics.value.splice(index, 1);
};

// 添加自定义话题
const addCustomTopic = () => {
  const topic = customTopic.value.trim();
  if (topic) {
    // 检查是否已添加该话题
    if (!selectedTopics.value.includes(topic)) {
      selectedTopics.value.push(topic);

      // 更新最近使用的话题
      if (!recentTopics.value.includes(topic)) {
        recentTopics.value.unshift(topic);
        if (recentTopics.value.length > 10) {
          recentTopics.value.pop();
        }
      }
    }
    closeTopicPanel();
  }
};

// 发布动态
const publish = async () => {
  if (!canPublish.value) return;

  publishing.value = true;

  try {
    // 检查token是否存在
    const token = uni.getStorageSync('userToken');
    if (!token) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      publishing.value = false;
      return;
    }

    // 上传图片到云存储
    const uploadedImages = [];
    if (images.value.length > 0) {
      uni.showLoading({ title: '图片上传中...' });
      for (let i = 0; i < images.value.length; i++) {
        const imgPath = images.value[i];
        try {
          const uploadResult = await uniCloud.uploadFile({
            filePath: imgPath,
            cloudPath: `posts/${Date.now()}_${i}.${imgPath.match(/\.([^.]+)$/)?.[1] || 'jpg'}`,
            success: (res) => {
              console.log('图片上传成功:', res);
            },
            fail: (err) => {
              console.error('图片上传失败:', err);
              throw new Error('图片上传失败');
            }
          });
          uploadedImages.push(uploadResult.fileID);
        } catch (error) {
          console.error('图片上传失败:', error);
          throw new Error('图片上传失败');
        }
      }
      uni.hideLoading();
    }

    // 构建发布数据
    const postData = {
      content: content.value.trim(),
      images: uploadedImages,
      topics: selectedTopics.value,
      privacy: privacy.value,
      createTime: new Date().getTime()
    };

    console.log('发布的数据:', postData);

    // 调用云函数发布动态
    const result = await uniCloud.callFunction({
      name: 'publish-post',
      data: postData,
      success: (res) => {
        console.log('发布动态成功:', res);
      },
      fail: (err) => {
        console.error('发布动态失败:', err);
        throw new Error('发布失败，请重试');
      }
    });

    if (result.result.code !== 0) {
      throw new Error(result.result.message || '发布失败，请重试');
    }

    // 发布成功
    uni.showToast({
      title: '发布成功',
      icon: 'success',
      duration: 1500,
      success: () => {
        setTimeout(() => {
          // 返回动态页面
          uni.navigateBack();
        }, 1500);
      }
    });

  } catch (error) {
    console.error('发布失败:', error);
    uni.showToast({
      title: error.message || '发布失败，请重试',
      icon: 'none'
    });
  } finally {
    publishing.value = false;
  }
};
</script>

<style scoped>
.publish-container {
  min-height: 100vh;
  background-color: #f7f7f7;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100rpx;
  background-color: white;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.cancel-text {
  font-size: 32rpx;
  color: #666;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.publish-text {
  font-size: 32rpx;
  color: #6d4aff;
  font-weight: bold;
}

.publish-text.disabled {
  color: #c8bfff;
}

/* 内容输入区域 */
.content-input-section {
  background-color: white;
  padding: 20rpx 30rpx;
  border-bottom: 10rpx solid #f7f7f7;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 15rpx;
  background-color: #f5f5f5;
}

.user-name {
  font-size: 28rpx;
  color: #333;
}

.content-textarea {
  width: 100%;
  font-size: 30rpx;
  color: #333;
  line-height: 48rpx;
  padding: 0;
  border: none;
  background-color: transparent;
  resize: none;
  min-height: 200rpx;
}

.content-textarea::-webkit-input-placeholder {
  color: #999;
}

.word-count {
  display: block;
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

/* 图片选择区域 */
.image-select-section {
  background-color: white;
  padding: 20rpx 30rpx 30rpx;
  border-bottom: 10rpx solid #f7f7f7;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 15rpx;
}

.image-item {
  width: 180rpx;
  height: 180rpx;
  position: relative;
  border-radius: 12rpx;
  overflow: hidden;
}

.upload-btn {
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 2rpx dashed #d9d9d9;
}

.upload-icon {
  font-size: 60rpx;
  color: #999;
}

.selected-image {
  width: 100%;
  height: 100%;
}

.delete-icon {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
}

.image-tip {
  font-size: 24rpx;
  color: #999;
}

/* 添加话题区域 */
.topic-section {
  background-color: white;
  padding: 20rpx 30rpx 30rpx;
  border-bottom: 10rpx solid #f7f7f7;
}

.topic-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.topic-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.topic-item {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  position: relative;
}

.topic-text {
  font-size: 26rpx;
  color: #6d4aff;
}

.topic-delete {
  margin-left: 10rpx;
  color: #999;
  font-size: 28rpx;
}

.add-topic {
  background-color: transparent;
  border: 2rpx dashed #d9d9d9;
}

.add-topic-text {
  font-size: 26rpx;
  color: #999;
}

/* 隐私设置 */
.privacy-section {
  background-color: white;
  padding: 20rpx 30rpx;
}

.privacy-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.privacy-options {
  display: flex;
  gap: 30rpx;
}

.privacy-option {
  display: flex;
  align-items: center;
  padding: 10rpx 30rpx;
  border: 2rpx solid #e8e8e8;
  border-radius: 40rpx;
  gap: 10rpx;
}

.privacy-option.active {
  border-color: #6d4aff;
  background-color: #f0efff;
}

.privacy-option text {
  font-size: 28rpx;
  color: #333;
}

.privacy-option.active text {
  color: #6d4aff;
}

.selected-icon {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
}

/* 话题选择面板 */
.topic-panel {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;
  padding: 20rpx;
  max-height: 70vh;
  overflow-y: auto;
  z-index: 200;
  box-shadow: 0 -10rpx 40rpx rgba(0, 0, 0, 0.1);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 20rpx;
}

.panel-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.panel-close {
  font-size: 40rpx;
  color: #999;
}

.hot-topics,
.recent-topics {
  margin-bottom: 30rpx;
}

.hot-topics-title,
.recent-topics-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.hot-topics-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.hot-topic-item {
  background-color: #f5f5f5;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.hot-topic-name {
  font-size: 26rpx;
  color: #6d4aff;
}

.hot-topic-count {
  font-size: 22rpx;
  color: #999;
}

.recent-topics-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.recent-topic-item {
  background-color: #f5f5f5;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
}

.recent-topic-name {
  font-size: 26rpx;
  color: #6d4aff;
}

.custom-topic {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.custom-topic-input {
  flex: 1;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  padding: 0 30rpx;
  height: 80rpx;
  font-size: 28rpx;
  color: #333;
}

.custom-topic-btn {
  padding: 0 30rpx;
  height: 80rpx;
  background-color: #6d4aff;
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 28rpx;
}

.custom-topic-btn.disabled {
  background-color: #c8bfff;
  color: #e6e1ff;
}

/* 发布中遮罩 */
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 300;
}

.loading-content {
  background-color: rgba(0, 0, 0, 0.7);
  padding: 30rpx 60rpx;
  border-radius: 15rpx;
}

.loading-text {
  color: white;
  font-size: 28rpx;
}
</style>